package com.hubu.thread.pattern;
/**
 *
 *
 *两阶段终结模式
 * 优雅打断一个运行中的线程
 */
public class Monitor {
    private Thread thread;
    private volatile boolean stop=false;
    public void start(){
        thread =new Thread(()->{
            while(true){
                //如果当前线程被打断之后，退出循环
//                if(Thread.currentThread().isInterrupted()) {
//                    break;
//                }

                if(stop){
                    break;
                }
                try {
                    System.out.println("线程处理工作");
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    //如果线程在睡眠过程中被打断
                    thread.interrupt();
                    e.printStackTrace();
                }
            }
        });
        thread.start();
    }
    public void stop(){
        //打断线程
        thread.interrupt();
        stop=true;
    }
    public static void main(String[] args) {
        Monitor monitor=new Monitor();
        monitor.start();

        try {
            Thread.sleep(3000);
            monitor.stop();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
